<template>
  <div class="chat" @click="hideEmoji">
    <div class="chat-left">
      <div class="chat-left-head">
        <div>
          <el-input placeholder="搜索" v-model="input" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <span title="发起群聊" @click="showNewRoom">+</span>
      </div>
      <div :class="selectedClass(conversation.id)"
           v-for="conversation in conversations" :key="conversation.id" @click="selectConversation(conversation)">
        <el-row style="font-size: 15px">
          <el-col :span="5">
            <el-badge :value="conversation.unreadMsgSum" class="item"
                      :hidden="conversation.unreadMsgSum === 0 ? true : false">
              <img :src="conversation.avatar" class="chat-left-item-avatar">
            </el-badge>
          </el-col>
          <el-col :span="19">
            <el-row>
              <el-col :span="18">
                <span style="display: inline-block;width: 130px;font-size: 14px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{conversation.comment}}</span>
                <div class="chat-left-item-content"
                     style="color: #999999;margin: 3px 0 0 0;font-size: 13px;width: 170px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"
                     v-html="conversation.content">
                </div>
              </el-col>
              <el-col :span="6" >
                <span style="color: #999999;font-size: 10px">{{diffTime(conversation)}}</span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="chat-right" @click="clearUnreadMsg" v-if="selectedConversation">
      <div class="chat-right-head">
        <span v-if="selectedConversation.chatType === 1" style="display: flex">
          <span style="display: inline-block;max-width: 150px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{ selectedConversation.comment}}</span>
          <span>{{'(' + selectedConversation.memberNumber + ')'}}</span>
        </span>
        <span v-else>{{selectedConversation.comment}}</span>
        <span v-if="selectedConversation.chatType === 1" class="chat-right-head-right el-icon-more" title="聊天信息" @click="showGroupInfo"></span>
      </div>
      <div class="chat-right-mid" ref="chatWrapper">
        <div style="position: relative;" class="chat-right-mid-left" v-for="(message,index) in selectedConversation.messages" :key="index"
             v-if="message.senderId!==currentUser.id">
          <span v-if="showDate(message)" style="display: inline-block;position: absolute; left: 50%;transform: translate(-50%,-100%);padding: 3px 5px;border-radius: 2px;background-color: #dadada;color: white;font-size: 14px">{{chatDateFormat(message.date)}}</span>
          <div style="display: inline-block">
            <!--群聊显示备注或昵称-->
            <div v-if="message.chatType === 1" style="position: relative;top: -6px;margin-left: 15px;font-size: 13px;color: #b2b2b2">{{ message.comment }}</div>
            <!--                文字消息开始-->
            <div v-if="message.type == 0" ref="content" style="display: inline-block;position: relative;padding: 7px;margin-left: 15px;max-width: 300px;border-radius: 5px;font-size: 15px;background-color: white">
              <div style="position: absolute; top: 17px;left: -12px;transform: translateY(-50%);border-left: 6px solid transparent;
                  border-bottom: 6px solid transparent;border-right: 6px solid white;border-top: 6px solid transparent;"></div>
              <div class="chat-content-text" v-html="message.content"></div>
            </div>
            <!--                文字消息结束-->
            <!--                文件消息开始-->
            <div v-if="message.type == 3" @click="downloadFile(message.content.url)" ref="content" style="display: inline-block;position: relative;padding: 7px;margin-left: 15px;max-width: 300px;border-radius: 5px;font-size: 15px;background-color: white;cursor: pointer" :title="message.content.name">
              <div style="position: absolute; top: 17px;left: -12px;transform: translateY(-50%);border-left: 6px solid transparent;
                  border-bottom: 6px solid transparent;border-right: 6px solid white;border-top: 6px solid transparent;"></div>
              <div style="width: 200px;margin-top: 5px;margin-left: 10px">
                <el-row>
                  <el-col :span="16">
                  <span
                      style="font-size: 15px;display: -webkit-box;-webkit-line-clamp:2;overflow: hidden;-webkit-box-orient: vertical">{{message.content.name}}</span>
                    <span style="font-size: 13px;color: #999">{{message.content.size}}</span>
                  </el-col>
                  <el-col :span="8">
                    <img style="margin-left: 15px" src="../assets/ppt.png" v-if="message.content.suffix=='pptx'">
                    <img style="margin-left: 15px" src="../assets/word.png" v-if="message.content.suffix=='docx'">
                    <img style="margin-left: 15px" src="../assets/pdf.png" v-if="message.content.suffix=='pdf'">
                    <img style="margin-left: 15px" src="../assets/package.png" v-if="message.content.suffix=='zip'">
                    <img style="margin-left: 15px" src="../assets/excel.png" v-if="message.content.suffix=='xlsx'">
                    <img style="margin-left: 15px" src="../assets/unknown.png" v-if="message.content.suffix!=='xlsx' && message.content.suffix!=='pptx' && message.content.suffix!=='doc' && message.content.suffix!=='zip'">
                  </el-col>
                </el-row>
                <p style="font-size: 12px;color: #999;margin-top: 5px">微信网页版</p>
              </div>
            </div>
            <!--                文件消息结束-->
            <!--                图片消息开始-->
            <div v-if="message.type == 1" style="display: inline-block;position: relative;padding: 0 7px 7px;margin-left: 15px;max-width: 300px;border-radius: 5px;font-size: 15px;background: none;">
              <el-image style="width:200px;border-radius: 5px"
                        :src="message.content"
                        :preview-src-list="[message.content]">
              </el-image>
            </div>
            <!--                图片消息结束-->
            <!--                视频消息开始-->
            <div v-if="message.type == 2" style="display: inline-block;position: relative;padding: 0 7px 7px;margin-left: 15px;max-width: 300px;border-radius: 5px;font-size: 15px;background: none;">
              <video style="width: 200px;border-radius: 5px" :src="message.content" controls></video>
            </div>
            <!--                视频消息结束-->
            <!--                语音消息开始-->
            <div v-if="message.type == 4" @click="readMessage(message)" ref="content" style="display: inline-block;position: relative;padding: 7px;margin-left: 15px;max-width: 300px;border-radius: 5px;font-size: 15px;background-color: white">
              <div style="position: absolute; top: 17px;left: -12px;transform: translateY(-50%);border-left: 6px solid transparent;
                  border-bottom: 6px solid transparent;border-right: 6px solid white;border-top: 6px solid transparent;"></div>
              <span v-if="message.read === 0" style="position: absolute;right: -10px;transform: translate(50%, 50%);width: 10px;height: 10px;border-radius: 50%;background-color: red"></span>
              <audio-message :src="message.content" :position="'left'"></audio-message>
            </div>
            <!--                语音消息结束-->
          </div>
          <img :src="message.senderAvatar">
        </div>
        <div style="position: relative" class="chat-right-mid-right" v-else>
          <span v-if="showDate(message)" style="display: inline-block;position: absolute; left: 50%;transform: translate(-50%,-100%);padding: 3px 5px;border-radius: 2px;background-color: #dadada;color: white;font-size: 14px">{{chatDateFormat(message.date)}}</span>
          <img :src="currentUser.avatar">
         <!--                文字消息开始-->
          <div class="chat-right-mid-right-content" ref="content" style="position: relative" v-if="message.type == 0">
            <i class="iconfont icon-fail" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);color: red" v-if="message.status == 2"></i>
            <i class="el-icon-loading" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);" v-if="message.status == 0"></i>
            <div style="position: absolute; top: 17px;right: -12px;transform: translateY(-50%);border-left: 6px solid #95ec69;
                  border-bottom: 6px solid transparent;border-right: 6px solid transparent;border-top: 6px solid transparent;"></div>
            <div class="chat-right-mid-right-content-text" v-html="message.content"></div>
          </div>
          <!--                文字消息结束-->
          <!--                语音消息开始-->
          <div ref="content" style="position: relative" v-if="message.type == 4">
            <i class="iconfont icon-fail" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);color: red" v-if="message.status == 2"></i>
            <i class="el-icon-loading" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);" v-if="message.status == 0"></i>
            <div style="position: absolute; top: 17px;right: -12px;transform: translateY(-50%);border-left: 6px solid #95ec69;
                  border-bottom: 6px solid transparent;border-right: 6px solid transparent;border-top: 6px solid transparent;"></div>
            <audio-message :src="message.content" :position="'right'"></audio-message>
          </div>
          <!--                语音消息结束-->
          <!--                文件消息开始-->
          <div ref="content" style="position: relative;background: white" v-if="message.type == 3" :title="message.content.name">
            <i class="iconfont icon-fail" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);color: red" v-if="message.status == 2"></i>
            <i class="el-icon-loading" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);" v-if="message.status == 0"></i>
            <div style="position: absolute; top: 17px;right: -12px;transform: translateY(-50%);border-left: 6px solid white;
                  border-bottom: 6px solid transparent;border-right: 6px solid transparent;border-top: 6px solid transparent;"></div>
            <div style="width: 200px;margin-top: 5px;margin-left: 10px">
              <el-row>
                <el-col :span="16">
                  <span
                      style="font-size: 15px;display: -webkit-box;-webkit-line-clamp:2;overflow: hidden;-webkit-box-orient: vertical">{{message.content.name}}</span>
                  <span style="font-size: 13px;color: #999">{{message.content.size}}</span>
                </el-col>
                <el-col :span="8">
                  <img style="margin-left: 15px" src="../assets/ppt.png" v-if="message.content.suffix=='pptx'">
                  <img style="margin-left: 15px" src="../assets/word.png" v-if="message.content.suffix=='docx'">
                  <img style="margin-left: 15px" src="../assets/pdf.png" v-if="message.content.suffix=='pdf'">
                  <img style="margin-left: 15px" src="../assets/package.png" v-if="message.content.suffix=='zip'">
                  <img style="margin-left: 15px" src="../assets/excel.png" v-if="message.content.suffix=='xlsx'">
                  <img style="margin-left: 15px" src="../assets/unknown.png" v-if="message.content.suffix!=='xlsx' && message.content.suffix!=='pptx' && message.content.suffix!=='doc' && message.content.suffix!=='zip'">
                </el-col>
              </el-row>
              <p style="font-size: 12px;color: #999;margin-top: 5px">微信网页版</p>
            </div>
          </div>
          <!--                文件消息结束-->
          <!--                图片消息开始-->
          <div style="background: none;padding-top: 0;position: relative" v-if="message.type == 1">
            <i class="iconfont icon-fail" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);color: red" v-if="message.status == 2"></i>
            <i class="el-icon-loading" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);" v-if="message.status == 0"></i>
<!--            <img style="width:200px;border-radius: 5px" :src="message.content">-->
            <el-image style="width:200px;border-radius: 5px"
                      :src="message.content"
                      :preview-src-list="[message.content]">
            </el-image>
          </div>
          <!--                图片消息结束-->
          <!--                视频消息开始-->
          <div style="background: none;padding-top: 0;position: relative" v-if="message.type == 2">
            <i class="iconfont icon-fail" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);color: red" v-if="message.status == 2"></i>
            <i class="el-icon-loading" style="position: absolute;left: -18px;top: 50%;
                  transform: translate(-50%,-50%);" v-if="message.status == 0"></i>
            <video style="width: 200px;border-radius: 5px" :src="message.content" controls></video>
          </div>
          <!--                视频消息结束-->
        </div>
      </div>
      <div class="chat-right-bottom">
        <div class="chat-right-bottom-menu">
          <div>
            <div @click.stop class="face" v-show="emojiVisible">
              <emoji @select="selectEmoji"></emoji>
            </div>
            <div class="chat-right-bottom-menu-item iconfont icon-expression" title="表情" @click="showEmoji" @click.stop></div>
            <div class="chat-right-bottom-menu-item iconfont icon-file" title="发送文件" @click="$refs.fileInput.click()">
              <input type="file" ref="fileInput" style="display: none" @change="uploadFile">
            </div>
            <div class="chat-right-bottom-menu-item iconfont icon-scissors" title="截图"></div>
            <div class="chat-right-bottom-menu-item iconfont icon-record" title="聊天记录"></div>
          </div>
          <div>
            <div class="chat-right-bottom-menu-item iconfont icon-sound" title="发语音" @click="showMicrophone"></div>
            <div class="chat-right-bottom-menu-item iconfont icon-audio" title="语音聊天"></div>
            <div class="chat-right-bottom-menu-item iconfont icon-video" title="视频聊天"></div>
          </div>
        </div>
        <div class="chat-right-bottom-input">
          <div id="editor"></div>
          <button @click="sendMessage">发送(S)</button>
        </div>
      </div>
    </div>
    <div class="chat-right iconfont icon-chat" style="display: flex;align-items: center;justify-content: space-around;font-size: 120px;color: #ececec" v-else></div>
    <new-room ref="newroom" :users="users" :type="type"></new-room>
    <group-info ref="groupinfo" v-if="selectedConversation" :id="selectedConversation.id" @getInfo="changeMember"></group-info>
    <microphone v-if="microphoneVisible" @hide="showMicrophone" @getAudio="sendAudio"></microphone>
  </div>
</template>
<script>
import Quill from 'quill'
import NewRoom from './NewRoom'
import GroupInfo from './GroupInfo'
import AudioMessage from './AudioMessage.vue'
import Microphone from './Microphone.vue'
import Emoji from './Emoji'

export default ({
  name: 'Chat',
  data () {
    return {
      input: '',
      num: 5,
      currentUser: this.$store.state.currentUser,
      selectedConversation: null,
      conversations: [
        {
          userName: '',
          id: 0,
          input: '',
          avatar: '', // 会话头像(私聊或群聊)
          unreadMsgSum: 0,
          messages: [
            {
              id: 0,
              type: 0, // 消息类型，0表示文字（含有表情包），1表示图片，2表示视频，3表示文件，4表示语音
              senderAvatar: '', // 发消息者的头像资源
              chatType: 0, // 0表示私聊,1表示群聊
              senderId: 0, // 发送者id
              receiverId: 0, // 接收者id
              date: null, // 时间
              status: 0, // 消息状态，0表示发送中，1表示发送成功，2表示发送失败
              read: 0, // 0表示未读，1表示已读
              content: { // type=3时，消息体为对象，否则为字符串
                size: 0,
                name: '',
                suffix: '',
                url: '' // 文件资源路径,用于下载
              }
            }
          ]
        }
      ],
      socket: null,
      emojiVisible: false,
      microphoneVisible: false,
      quill: null,
      content: '', // 输入框内容,
      users: [],
      type: 0
    }
  },
  created () {
    this.loadData()
    this.connect()
  },
  mounted () {
    let id = this.$route.params.id
    this.startConversation(id)
  },
  beforeDestroy () {
  },
  methods: {
    loadData () {
      this.currentUser = this.$store.state.currentUser
      this.conversations = this.$store.state.conversations
      this.setSelectedConversation(this.$store.state.selectedConversation)
    },
    startConversation (id) {
      if (id === undefined) {
        return
      }
      let user = this.getUser(id)
      let conversation = {
        id: user.id,
        avatar: user.avatar,
        comment: user.comment,
        chatType: 0,
        input: '',
        content: '',
        unreadMsgSum: 0,
        messages: []
      }
      // 先查询会话是否存在
      for (let i = 0; i < this.conversations.length; i++) {
        if (this.conversations[i].id === user.id) {
          conversation = this.conversations[i]
          break
        }
      }
      this.toConversationsTop(conversation)
      this.setSelectedConversation(conversation)

      this.$store.commit('setConversations', this.conversations)
    },
    selectConversation (conversation) {
      // 保存旧会话
      if (this.selectedConversation !== null) {
        let index = this.indexOfConversation(this.selectedConversation.id)
        this.conversations[index].input = this.quill.root.innerHTML
      }

      // 选中新会话
      conversation.unreadMsgSum = 0
      this.setSelectedConversation(conversation)
      this.countUnreadMsg()
    },
    setSelectedConversation (conversation) {
      this.selectedConversation = conversation
      this.$store.commit('setSelectedConversation', this.selectedConversation)

      if (this.selectedConversation !== null && this.quill === null) {
        this.$nextTick(() => {
          this.quill = new Quill('#editor', {
            theme: 'snow',
            placeholder: '请输入内容',
            modules: {
              toolbar: []
            }
          })
          this.quill.root.innerHTML = conversation.input
        })
      }
    },
    // 选中会话的样式
    selectedClass (conversationId) {
      if (this.selectedConversation === null || this.selectedConversation.id !== conversationId) {
        return 'chat-left-item'
      } else {
        return 'chat-left-item-active chat-left-item'
      }
    },
    indexOfConversation (id) {
      let index
      for (let i = 0; i < this.conversations.length; i++) {
        if (id === this.conversations[i].id) {
          index = i
          break
        }
      }
      return index
    },
    toConversationsTop (conversation) {
      let index = this.indexOfConversation(conversation.id)
      // 已存在先出会话数组,再置顶
      if (index !== undefined && index !== -1) {
        this.conversations.splice(index, 1)
      }
      this.conversations.unshift(conversation)
    },
    // 接收信息,添加回话
    async addConversation (message) {
      if (message.chatType === 1 && message.senderId === this.currentUser.id) {
        return
      }

      let content = ''
      let id = 0
      if (message.chatType === 1) { // 群聊消息
        content = message.comment + ': '
        id = message.receiverId
      } else if (message.chatType === 0) { // 私聊消息
        id = message.senderId
        let user = this.getUser(id)
        message.comment = user.comment
      }

      if (message.type === 0) {
        content = content + message.content
      } else if (message.type === 1) {
        content = content + '[图片]'
      } else if (message.type === 2) {
        content = content + '[视频]'
      } else if (message.type === 3) {
        content = content + '[文件]'
      } else if (message.type === 4) {
        content = content + '[语音]'
      }
      let conversation = {
        id,
        avatar: message.senderAvatar,
        chatType: message.chatType,
        comment: message.comment,
        unreadMsgSum: 0,
        input: '',
        messages: []
      }

      // 查找会话
      let i
      for (i = 0; i < this.conversations.length; i++) {
        if (this.conversations[i].id === id) {
          conversation = this.conversations[i]
          break
        }
      }
      // 群聊会话初次创建, 请求群信息
      if (i === this.conversations.length && message.chatType === 1) {
        const response = await this.axios.post(`/api/v1/group/${id}`)
        if (response.data.code === 1) {
          conversation.comment = response.data.data.name
          conversation.avatar = response.data.data.groupAvatar
          conversation.memberNumber = response.data.data.groupMemberCount
        }
      }

      conversation.messages.push(message)
      conversation.content = content
      conversation.unreadMsgSum++

      this.toConversationsTop(conversation)
      this.countUnreadMsg()

      this.$store.commit('setConversations', this.conversations)
    },
    // 发消息时,添加消息
    addMessage (message) {
      let content = ''
      if (message.type === 0) {
        content = message.content
      } else if (message.type === 1) {
        content = '[图片]'
      } else if (message.type === 2) {
        content = '[视频]'
      } else if (message.type === 3) {
        content = '[文件]'
      } else if (message.type === 4) {
        content = '[语音]'
      }
      this.selectedConversation.content = content

      if (this.selectedConversation.messages === undefined) {
        this.selectedConversation.messages = []
      }
      this.selectedConversation.messages.push(message)
      this.toConversationsTop(this.selectedConversation)
    },
    // 已读语音消息
    readMessage (message) {
      message.read = 1
    },
    sendMessage () {
      let content = this.quill.root.innerHTML
      if (content === '<p><br></p>') {
        return
      }
      content = this.getContent(content)
      let message = {
        id: this.getMessageId(),
        type: 0,
        chatType: this.selectedConversation.chatType, // 聊天消息类型,0表示私聊,1表示群聊
        comment: this.selectedConversation.chatType === 1 ? this.currentUser.nickname : '', // 聊天消息类型,0表示私聊,1表示群聊
        senderAvatar: this.currentUser.avatar,
        senderId: this.currentUser.id,
        receiverId: this.selectedConversation.id,
        date: new Date(),
        content,
        status: 0
      }
      this.setInputContent('')
      this.addMessage(message)

      this.sendMessageByWebsocket(message)
    },
    // 使用正则表达式和match()方法提取<p>标签的内容
    getContent (str) {
      let regex = /<p>(.*?)<\/p>/ // 匹配<p>标签及其内容
      let match = str.match(regex) // 执行匹配操作

      return match[1]
    },
    getMessageId () {
      let currentTime = new Date()
      return currentTime.getTime()
    },
    countUnreadMsg () {
      let sum = 0
      for (let i = 0; i < this.conversations.length; i++) {
        sum += this.conversations[i].unreadMsgSum
      }
      this.$store.commit('setUnreadMsgSum', sum)
    },
    clearUnreadMsg () {
      this.selectedConversation.unreadMsgSum = 0
      this.countUnreadMsg()
    },
    getUser (id) {
      let users = this.$store.state.users
      for (let i = 0; i < users.length; i++) {
        if (users[i].id === id) {
          return users[i]
        }
      }
    },
    // 时间格式化
    diffTime (conversation) {
      let date = conversation.messages[0] ? conversation.messages[conversation.messages.length - 1].date : new Date()
      return this.conversationDateFormat(date)
    },
    conversationDateFormat (time) {
      let past = new Date(time)
      let pastDate = past.getDate()
      let pastMonth = past.getMonth()
      let pastYear = past.getFullYear()

      let now = new Date()
      let nowDate = now.getDate()
      let nowMonth = now.getMonth()
      let nowYear = now.getFullYear()

      if (pastYear === nowYear && pastMonth === nowMonth && nowDate === pastDate) {
        let hours = past.getHours() < 10 ? '0' + past.getHours() : past.getHours()
        let minutes = past.getMinutes() < 10 ? '0' + past.getMinutes() : past.getMinutes()
        return hours + ':' + minutes
      } else if (pastYear === nowYear && pastMonth === nowMonth && (nowDate - pastDate) === 1) {
        return '昨天'
      } else if (pastYear === nowYear && pastMonth === nowMonth &&
          (nowDate - pastDate) > 1 && (nowDate - pastDate) < 7) {
        let days = ['天', '一', '二', '三', '四', '五', '六']
        let day = past.getDay()
        return '星期' + days[day]
      } else {
        let first = parseInt(pastYear / 10 % 10)
        let second = pastYear % 10
        let yearStr = ''
        yearStr = yearStr + first + second
        let month = pastMonth + 1
        return yearStr + '/' + month + '/' + pastDate
      }
    },
    chatDateFormat (time) {
      let past = new Date(time)
      let pastDate = past.getDate()
      let pastMonth = past.getMonth()
      let pastYear = past.getFullYear()

      let now = new Date()
      let nowDate = now.getDate()
      let nowMonth = now.getMonth()
      let nowYear = now.getFullYear()

      let hours = past.getHours()
      let minutes = past.getMinutes() < 10 ? '0' + past.getMinutes() : past.getMinutes()

      if (pastYear === nowYear && pastMonth === nowMonth && nowDate === pastDate) {
        return hours + ':' + minutes
      } else if (pastYear === nowYear && pastMonth === nowMonth && (nowDate - pastDate) === 1) {
        return '昨天 ' + hours + ':' + minutes
      } else if (pastYear === nowYear && pastMonth === nowMonth &&
          (nowDate - pastDate) > 1 && (nowDate - pastDate) < 7) {
        let days = ['天', '一', '二', '三', '四', '五', '六']
        let day = past.getDay()
        return '星期' + days[day] + ' ' + hours + ':' + minutes
      } else {
        let month = pastMonth + 1
        return pastYear + '年' + month + '月' + pastDate + '日' + ' ' + hours + ':' + minutes
      }
    },
    showDate (message) {
      let messages = this.selectedConversation.messages
      let index = messages.indexOf(message)
      if (index === 0) {
        return true
      } else {
        let lastDate = this.getTime(messages[index - 1].date)
        let currentDate = this.getTime(messages[index].date)
        if (lastDate === currentDate) {
          return false
        } else {
          return true
        }
      }
    },
    getTime (time) {
      let date = new Date(time)
      let year = date.getFullYear()
      let month = date.getMonth()
      let day = date.getDate()
      let hours = date.getHours()
      let minutes = date.getMinutes()

      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
    },
    setInputContent (content) {
      this.quill.root.innerHTML = content
      this.content = content
    },
    // Websocket连接
    connect () {
      this.socket = this.$store.state.socket
      if (this.socket === null || this.socket === undefined) {
        // 新建Websocket连接
        this.socket = new WebSocket(`ws://176.125.55.210:8091/websocket?token=${this.currentUser.token}`)
        // Websocket连接成功事件
        this.socket.onopen = function (event) {
          this.$message.success('欢迎回来!')
          console.log('Connected to websocket')
        }.bind(this)

        // Websocket接收消息事件
        this.socket.onmessage = (event) => {
          let data = event.data
          console.log('Received message:', data)
          let message = this.parseMessage(data)

          if (message.chatType === 101) { // 申请添加好友消息
            message = message.content
            message.accept = 0
            message.read = 0
            this.$store.commit('addFriendRequestMsg', message)
          } else if (message.chatType === 0 || message.chatType === 1 || message.chatType === 9) { // 聊天消息
            // 添加好友初次问候(由系统发起)
            if (message.chatType === 9) {
              message.chatType = 0
              this.addUser(message)
            }
            this.addConversation(message)
          } else if (message.chatType === 110 || message.chatType === 111) { // 110表示点赞，111表示评论
            console.log(message)
            this.addMomentMsgArr(message)
          }
        }

        // Websocket连接错误事件
        this.socket.onerror = function (event) {
          this.$message.error('网络错误!')
          console.error('Websocket error observed: ', event)
        }.bind(this)
        // Websocket断开连接事件
        // 绑定vue对象后，在此方法中this指向vue对象
        this.socket.onclose = function (event) {
          this.$message.error('您已掉线!')
          console.error('Websocket close')
          this.socket = null
          this.$store.commit('setSocket', null)
        }.bind(this)
      }
      // 全局保存socket
      this.$store.commit('setSocket', this.socket)
    },
    parseMessage (data) {
      let message = JSON.parse(data)
      if (message.type === 3) {
        let content = JSON.parse(message.content)
        message.content = content
      }
      return message
    },
    reconnect () {
      this.$store.commit('setSocket', null)
      this.connect()
    },
    // 向好友数组添加好友
    addUser (message) {
      let user = {id: message.senderId, avatar: message.senderAvatar, comment: message.comment}
      let users = this.$store.state.users
      users.unshift(user)
      this.$store.commit('setUsers', users)
    },
    scrollToEnd () {
      if (this.selectedConversation !== null) {
        const el = this.$refs.chatWrapper
        el.scrollTop = el.scrollHeight
      }
    },
    showMicrophone () {
      this.microphoneVisible = !this.microphoneVisible
    },
    showGroupInfo () {
      this.$refs.groupinfo.show()
    },
    showEmoji () {
      this.emojiVisible = !this.emojiVisible
    },
    hideEmoji () {
      this.emojiVisible = false
    },
    selectEmoji (url) {
      this.hideEmoji()
      const range = this.quill.getSelection(true)
      // 插入表情包
      this.quill.insertEmbed(range.index, 'image', url)
      this.content = this.quill.root.innerHTML
      // 将光标移到最后
      this.quill.setSelection(range.index + 1, 0)
    },
    async uploadFile () {
      const fileInput = this.$refs.fileInput
      const file = fileInput.files[0]
      const fileExtension = file.name.split('.').pop()

      let message = {
        id: this.getMessageId(),
        senderAvatar: this.currentUser.avatar,
        senderId: this.currentUser.id,
        chatType: this.selectedConversation.chatType,
        comment: this.selectedConversation.chatType === 1 ? this.currentUser.nickname : '',
        receiverId: this.selectedConversation.id,
        date: new Date(),
        status: 0
      }
      if (fileExtension === 'jpeg' || fileExtension === 'jpg' || fileExtension === 'png') {
        message.type = 1
        message.content = URL.createObjectURL(file)
      } else if (fileExtension === 'mp4') {
        message.type = 2
        message.content = URL.createObjectURL(file)
      } else {
        message.type = 3
        message.content = {name: file.name, size: this.fileSize(file.size), suffix: fileExtension, url: ''}
      }

      this.addMessage(message)

      let url
      try {
        const formData = new FormData()
        formData.append('file', file)
        const response = await this.axios.post('/api/v1/file/upload', formData, {
          headers: {
            'Content-type': 'multipart/form-data'
          }
        })
        if (response.data.code === 1) {
          url = response.data.data
        } else {
          message.status = 2
          return
        }
      } catch (error) {
        this.$message.error(error)
        message.status = 2
        return
      }

      if (message.type === 1 || message.type === 2) {
        message.content = url
      } else {
        message.content.url = url
      }

      this.sendMessageByWebsocket(message)
    },
    sendMessageByWebsocket (message) {
      try {
        let jsonStr = JSON.stringify(message)
        this.socket.send(jsonStr)
        message.status = 1
      } catch (error) {
        this.$message.error(error)
        console.error(error)
        message.status = 2
      }
    },
    fileSize (size) {
      size = (size / 1024).toFixed(1)
      if (size > 1024) {
        size = (size / 1024).toFixed(1)
        return size + 'M'
      }
      return size + 'K'
    },
    async sendAudio (audio) {
      // 关闭麦克风组件
      this.showMicrophone()
      let url = URL.createObjectURL(audio)
      let message = {
        id: 0,
        type: 4, // 消息类型，0表示文字（含有表情包），1表示图片，2表示视频，3表示文件，4表示语音
        senderAvatar: this.currentUser.avatar, // 发消息者的头像资源
        senderId: this.currentUser.id, // 发送者id
        receiverId: this.selectedConversation.id, // 接收者id
        chatType: this.selectedConversation.chatType,
        comment: this.selectedConversation.chatType === 1 ? this.currentUser.nickname : '',
        date: new Date(), // 时间
        status: 0, // 消息状态，0表示发送中，1表示发送成功，2表示发送失败
        read: 0, // 0表示未读，1表示已读
        content: url
      }
      this.addMessage(message)

      try {
        // 上传录音文件
        let formData = new FormData()
        formData.append('file', audio, 'audio.wav')
        const response = await this.axios.post('/api/v1/file/upload', formData, {
          headers: {
            'Content-type': 'multipart/form-data'
          }
        })
        if (response.data.code === 1) {
          url = response.data.data
        } else {
          message.status = 2
          return
        }
      } catch (error) {
        this.$message.error(error)
        message.status = 2
        return
      }

      this.sendMessageByWebsocket(message)
    },
    showNewRoom () {
      this.users = this.$store.state.users
      this.type = 0
      this.$refs.newroom.show()
    },
    changeMember (info) {
      this.users = info.users
      this.type = info.type
      this.$refs.newroom.show()
    },
    downloadFile (url) {
      window.open(url)
    },
    addMomentMsgArr (message) {
      let momentMsgArr = this.$store.state.momentMsgArr
      // 设置消息未读
      message.read = 0
      momentMsgArr.unshift(message)

      // 统计未读消息数
      let momentMsgSum = 0
      for (let i = 0; i < momentMsgArr.length; i++) {
        if (momentMsgArr[i].read === 0) {
          momentMsgSum++
        }
      }

      // 本地保存
      this.$store.commit('setMomentMsgArr', momentMsgArr)
      this.$store.commit('setMomentMsgSum', momentMsgSum)
    }
  },
  computed: {
  },
  watch: {
    conversations (newValue, oldValue) {
      this.$nextTick(() => {
        this.scrollToEnd()
      })
    },
    selectedConversation (newVale, oldValue) {
      this.$nextTick(() => {
        this.scrollToEnd()
      })
    }
  },
  components: {
    NewRoom,
    GroupInfo,
    Emoji,
    Microphone,
    AudioMessage
  }
})
</script>
<style lang="stylus" rel="stylesheet/stylus">
.ql-toolbar.ql-snow
  display none

.ql-clipboard
  display none

.ql-tooltip.ql-hidden
  display none

.ql-editor:focus
  outline none

.ql-editor p img
  vertical-align middle
  width 28px
  height 28px

.chat-left
  position fixed
  top 55px
  left 55px
  bottom 0
  width 250px
  overflow auto
  background-color #e4e5e6
  &::-webkit-scrollbar
    display none
  &-head
    position fixed
    top 0
    left 55px
    width 250px
    height 55px
    box-sizing border-box
    padding-top 10px
    padding-left 10px
    background-color #f6f6f6
  &-head > div
    display inline-block
    width 190px
    margin-right 8px
  &-head > span
    display inline-block
    width 25px
    height 25px
    line-height 25px
    font-size 20px
    text-align center
    color #545454
    border-radius 5px
    background-color #e2e2e2
    &:hover
      cursor pointer
      background-color #d1d1d1
  &-item
    position relative
    height 60px
    box-sizing border-box
    padding-left 10px
    padding-top 10px
    cursor default
    &:hover
      background-color #dcdad9
    &-active
      background-color #c5c5c6
    &-avatar
      width 40px
      height 40px
    &-content
      & p
        margin 0
        font-size 10px
      & img
        width 20px
        vertical-align middle

.chat-content-text img
  vertical-align middle
  width 28px
  height 28px
.chat-right
  position fixed
  top 0
  left 305px
  right 0
  bottom 0
  border-left 1px solid #d6d6d6

  &-head
    display flex
    justify-content space-between
    align-items center
    position fixed
    top 0
    right 0
    left 305px
    height 55px
    box-sizing border-box
    padding-left 20px
    line-height 55px
    font-size 20px
    background-color #f5f5f5
    border-bottom 1px solid #e7e7e7
    & span
      margin-right: 10px;
      cursor pointer
    &-right
      color #494949
      font-size 18px

  &-mid
    display flex
    flex-direction column
    position fixed
    top 55px
    bottom 145px
    left 305px
    right 0
    background-color #f5f5f5
    overflow auto
    &::-webkit-scrollbar
      display none
    &-left
      margin 20px
      & > img
        float left
        width 34px
        height 34px

    &-right
      margin 20px
      &-content
        &-text img
            vertical-align middle
            width 28px
            height 28px
      & > img
        float right
        width 34px
        height 34px
      & > div
        float right
        display inline-block
        max-width 300px
        border-radius 5px
        padding 7px
        margin-right 15px
        font-size 15px
        background-color #95ec69

  &-bottom
    position fixed
    bottom 0
    right 0
    left 305px
    height 145px

    &-menu
      display flex
      justify-content space-between
      align-items center
      height 40px
      padding-left 22px
      padding-right 10px
      margin 0

      .face
        position absolute
        top -370px
        transform translateX(-50%)

      &-item
        display inline-block
        color #535353
        font-size 20px
        margin-right 10px

        &:hover
          color black
          cursor pointer

    &-input
      position relative
      padding 0 20px

      & > div
        height 90px

      & > button
        position absolute
        bottom 10px
        right 50px
        width 100px
        height 30px
        line-height 30px
        font-size 15px
        color #38c179
        background-color #e9e9e9
        border-radius 5px
        border none

        &:hover
          cursor pointer
          background-color #d2d2d2
</style>
